/*
 * @Author: xyf
 * @Date: 2021-06-28 18:07:45
 * @LastEditTime: 2021-06-28 18:07:52
 * @LastEditors: xyf
 * @Description: axios二次封装
 */
import axios from 'axios'
import config from '@/config'
import { ElMessage } from 'element-plus'

const TOKEN_INVALID = 'Token认证失败，请重新登录'

// 创建axios实例，添加全局配置
let service = axios.create({
  baseURL: config.baseApi,
  timeout: 8000
})

// 请求拦截
service.interceptors.request.use((req) => {
  return req
})

// 响应拦截
service.interceptors.response.use((res) => {
  const { code, data, message } = res.data
  if (code === 200) {
    return res.data
  } else if (code === 401) {
    // 根据实际业务
    ElMessage.error(TOKEN_INVALID)
    return Promise.reject(TOKEN_INVALID)
  } else {
    ElMessage.error(message)
    return Promise.reject(message)
  }
})

/**
 * @description: 请求核心函数
 * @param {*} options - 请求配置
 */
function request(options) {
  options.method = options.method || 'get'
  if (options.method.toLowerCase() === 'get') options.params = options.data

  let isMock = config.mock
  if (typeof options.mock != 'undefined') {
    isMock = options.mock
  }

  // 避免生产环境调用mock
  if (config.env === 'production') {
    service.defaults.baseURL = config.baseApi
  } else {
    service.defaults.baseURL = isMock ? config.mockApi : config.baseApi
  }

  return service(options)
}

export default request
